// 请求通知权限
async function requestNotificationPermission() {
    try {
        // 优先使用Electron API
        if (window.electronAPI?.requestNotificationPermission) {
            const result = await window.electronAPI.requestNotificationPermission();
            console.log('Electron通知权限:', result);
            return result.success;
        }
        
        // 降级到浏览器通知
        if ('Notification' in window) {
            if (Notification.permission === 'default') {
                const permission = await Notification.requestPermission();
                return permission === 'granted';
            }
            return Notification.permission === 'granted';
        }
        
        return false;
    } catch (error) {
        console.error('请求通知权限时出错:', error);
        return false;
    }
}

// 为所有有效未来日程设置提醒
async function setupAllReminders() {
    try {
        const schedules = await getSchedulesFromStorage();
        const now = new Date();
        
        schedules.forEach(schedule => {
            if (schedule.reminder && !schedule.isCompleted) {
                const scheduleTime = new Date(`${schedule.date}T${schedule.time}`);
                if (scheduleTime > now) {
                    setReminder(schedule);
                }
            }
        });
        
        console.log('已为所有有效的未来日程设置提醒');
    } catch (error) {
        console.error('设置提醒时出错:', error);
    }
}

// 浏览器通知降级函数
function fallbackToBrowserNotification(schedule) {
    if ('Notification' in window) {
        if (Notification.permission === 'granted') {
            new Notification('日程提醒', {
                body: `您有一个即将开始的日程：${schedule.title}\n时间：${formatDate(schedule.date)} ${schedule.time}`,
                icon: '',
            });
        } else if (Notification.permission === 'default') {
            Notification.requestPermission();
        }
    }
}

// 优化日程提醒
function optimizeReminderFunction() {
    // 保存原始函数引用
    const originalSetReminder = window.setReminder;
    
    // 重写setReminder函数
    window.setReminder = function(schedule) {
        const reminderTime = new Date(`${schedule.date}T${schedule.time}`);
        const now = new Date();
        const timeDiff = reminderTime.getTime() - now.getTime();
        
        // 仅处理未来日程
        if (timeDiff > 0) {
            // 解析提醒时间（默认5分钟）
            const reminderMinutes = schedule.reminderTime ? parseInt(schedule.reminderTime.toString()) : 5;
            // 计算提前提醒时间
            const reminderTimeout = timeDiff - reminderMinutes * 60 * 1000;
            
            if (reminderTimeout > 0) {
                setTimeout(async () => {
                    // 显示应用内通知
                    showNotification(`您有一个即将开始的日程：${schedule.title}`, 'warning');
                    
                    try {
                        // 优先使用Electron通知
                        if (window.electronAPI?.showNotification) {
                            const result = await window.electronAPI.showNotification('日程提醒', {
                                body: `您有一个即将开始的日程：${schedule.title}\n时间：${formatDate(schedule.date)} ${schedule.time}`,
                                icon: '',
                                timeoutType: 'default',
                                hasReply: false,
                                urgency: 'critical'
                            });
                            
                            if (!result.success) {
                                console.log('Electron通知失败，尝试使用浏览器通知:', result.error);
                                fallbackToBrowserNotification(schedule);
                            }
                        } else {
                            fallbackToBrowserNotification(schedule);
                        }
                    } catch (error) {
                        console.error('显示通知时出错:', error);
                        fallbackToBrowserNotification(schedule);
                    }
                }, reminderTimeout);
            }
        }
    };
    
    // 优化showNotification函数
    const originalShowNotification = window.showNotification;
    window.showNotification = function(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.innerHTML = `
            <div class="flex items-center space-x-2">
                <i class="fa ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-exclamation-triangle'}"></i>
                <span>${message}</span>
            </div>
        `;
        
        // 设置唯一ID
        notification.id = `notification-${Date.now()}`;
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 点击关闭通知
        notification.addEventListener('click', () => {
            if (document.body.contains(notification)) {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(100%)';
                notification.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                
                setTimeout(() => {
                    if (document.body.contains(notification)) {
                        document.body.removeChild(notification);
                    }
                }, 300);
            }
        });
        
        // 3秒后自动关闭
        setTimeout(() => {
            if (document.body.contains(notification)) {
                notification.style.opacity = '0';
                notification.style.transform = 'translateX(100%)';
                notification.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                
                setTimeout(() => {
                    if (document.body.contains(notification)) {
                        document.body.removeChild(notification);
                    }
                }, 300);
            }
        }, 3000);
    };
    
    // 修改应用启动事件
    const originalDOMContentLoaded = window.onload;
    window.onload = async function() {
        originalDOMContentLoaded?.();
        
        // 请求通知权限并设置提醒
        const hasNotificationPermission = await requestNotificationPermission();
        console.log('通知权限状态:', hasNotificationPermission ? '已授予' : '未授予');
        
        if (hasNotificationPermission) {
            await setupAllReminders();
        }
    };
}

// 在DOM加载完成后执行优化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', optimizeReminderFunction);
} else {
    optimizeReminderFunction();
}